package com.specter.serv.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.specter.mvc.model.Response;
import com.specter.mvc.web.spring.ConventionController;
import com.specter.serv.service.BidpService;
import com.specter.utils.StringUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 项目本地及数据中台服务接口
 * 
 * @version 1.0
 * @since 2020-02-02
 * @author Liang.Wang
 */
@Slf4j
@Controller("serv-apis")
@RequestMapping("/serv/apis")
public class ApisController extends ConventionController {
	private @Autowired BidpService bidp;

	/**
	 * 获得所有Controller的配置情况，可以直接注入RequestHandlerMapping直接获取
	 * 
	 * @apiNote API资源
	 * @param request  req和res不用传值 {@link java.lang.Class}
	 * @param response req和res不用传值 {@link java.lang.Class}
	 * @return 根据配置情况返回内部api接口资源 {@link java.lang.Class}
	 */
	@Override
	@GetMapping("/mapping")
	public void mapping(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.mapping(request, response);
	}

	/**
	 * 通过服务器代理请求外网资源，以获取跨域资源
	 * 
	 * @param request  其中url被代理的地址
	 * @param response req和res不用传值
	 * @return 根据原资源的Content-Type返回相应结果
	 */

	@ResponseBody
	@RequestMapping("/gateway/**")
	public Response gateway(HttpServletRequest request, HttpServletResponse response) {
		// 1.获取接口标识（支持路径和Id模式）
		String path = StringUtils.substringAfter(request.getRequestURL().toString(), "/serv/apis/gateway");
		
		// 2.请求外网资源
		try {
			Object data = bidp.gws(path);
			return Response.success().data(data);
		} catch (Exception e) {
			log.error("请求代理错误", e);
			return Response.failure("请求代理错误");
		}
	}

}
